<?php
declare (strict_types = 1);

namespace app\admin\controller;
use app\admin\middleware\Auth;
use app\model\BannersModel;
use app\model\CourseBannersModel;
use app\model\CourseModel;
use app\model\CourseOperationsModel;
use app\model\RedisModel;
use think\App;
use think\facade\Db;

class CourseOperations extends Base {

    protected $middleware = [Auth::class];
    private $courseOperationsModel;

    private $req;


    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->courseOperationsModel = new CourseOperationsModel();

        $this->req =  request()->param();

        $this->isLogin();
    }

    /*
     * 获取所有banner
     * */

    public function getInfo()
    {
        $info = $this->courseOperationsModel->getInfo();

        return $this->succ($info);
    }



    public function edit()
    {
        if(!isset($this->req['name']) || empty($this->req['name'])){
            return $this->fail("名称不能为空");
        }

        if(!isset($this->req['course_id']) || empty($this->req['course_id'])){
            return $this->fail("请输入课程Id");
        }

        $courseInfo = (new CourseModel())->getInfo($this->req['course_id']);

        if(empty($courseInfo)){
            return $this->fail("课程不存在");
        }

        if(!isset($this->req['button_name']) || empty($this->req['button_name'])){
            return $this->fail("请输入按钮名称");
        }

        if(!isset($this->req['cover_img']) || empty($this->req['cover_img'])){
            return $this->fail("请上传封面图");
        }

        if(!isset($this->req['back_img']) || empty($this->req['back_img'])){
            return $this->fail("请上传背景图");
        }

        $addres = $this->courseOperationsModel->where("id",1)->save([
            "name" => $this->req['name'],
            "course_id" => $this->req['course_id'],
            "button_name" => $this->req['button_name'],
            "cover_img" => $this->req['cover_img'],
            "back_img" => $this->req['back_img'],
        ]);

        if($addres){
            $this->delAllCache();
            return $this->succ();
        }else{
            return $this->fail();
        }
    }



    public function delCache($id)
    {
        $redisModel = new RedisModel();

        return $redisModel->delete( $this->courseOperationsModel->cacheKey.$id);
    }


    public function delAllCache()
    {
        $redisModel = new RedisModel();

        return $redisModel->deleteAll( $this->courseOperationsModel->cacheKey);
    }

}
